
import numpy as np 
from casadi import *
from Parameters1D_casadi import *
from Model1D_casadi import *
import time

initTime = time.process_time()

soilPars = loamySoil()#The soil parameters
totalDepth, axialNodes, axialDistance, totalNodes = spatialVariables_1D()  #Spatial parameters
samplingTime, samplingTimeInternal, internalTimeSteps, totTimeSteps = temporalVariable() #time parameters



#Irrigation Amount
u=np.zeros( )
#Irrigation is performed once each day between 0:00 am and 0:06 am
u[1] = -1.0e-05
u[241] = -1.0e-05
u[481] = -1.0e-05
u[721] = -1.0e-05
u[961] = -1.0e-05
u[1201] = -1.0e-05




#The initial Condition
initCondition = 1.2*-0.8*np.ones(totalNodes)

#Arrays to store the results
headArray = np.zeros((totTimeSteps+1, totalNodes)) # Pressure head
headArray[0,:] = initCondition

volMoisture = np.zeros((totTimeSteps+1, totalNodes)) #Volumetric Mositure
volMoisture[0,:] = volMoistureAllNodes_1D(initCondition).full().ravel()





##Creating the Casadi integrator
#Symbolic variables

headSym = SX.sym('h', totalNodes)
inpSym = SX.sym('u', 1)

#Symbolic polar model
polarModelSym = RichardsPolar_1D(headSym, inpSym)


ODE = {'x': headSym, 'p': vertcat(inpSym), 'ode': polarModelSym}
opts = {'tf': samplingTimeInternal, 'regularity_check': True}

I = integrator('I', 'cvodes', ODE, opts)


def smallerTimeSteps(initHead, irrigAmnt):
    interHead = initHead
    for i in range(internalTimeSteps):
        intRes = I(x0=interHead, p=vertcat(irrigAmnt))
        interHead = intRes['xf'].full().ravel()
    return interHead


for i in range(1,2):


    #intRes = I(x0=headArray[i-1,:], p=vertcat(u[i-1], procNoise[i-1], cropCoeff[i-1], refEvap[i-1]))
    #headArray[i,:] = intRes['xf'].full().ravel()
    headArray[i,:] = smallerTimeSteps(headArray[i-1,:], (u[i-1]))
    volMoisture[i,:] = volMoistureAllNodes_1D(headArray[i,:]).full().ravel()

elapsedTime = time.process_time() - initTime

print(f"The model simulation takes {elapsedTime} seconds to run")